<template>
    <div>
        <!-- 更改 -->
		<el-dialog title="管理会员" :visible.sync="addFormVisible" @close="closeDialog"   center>
			<el-form :model="addForm" label-width="80px"  ref="addForm" label-position="left" inline>
				<el-col :span="24">
					<el-form-item label="会员编号" prop="number" v-if="addForm.number">
						<!-- <el-input v-model="addForm.number" auto-complete="off"></el-input> -->
						<div>{{addForm.number}}</div>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="手机" prop="phone" :disabled="false">
						<el-input v-model="addForm.phone" auto-complete="off"  style="width:200px"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="姓名" prop="realname" >
						<el-input v-model="addForm.realname" auto-complete="off"  style="width:200px"></el-input>

					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="身份证" prop="realname" >
						<el-input v-model="addForm.idCard" auto-complete="off" :disabled="addForm.is_vip==1" style="width:200px"></el-input>

					</el-form-item>
				</el-col>
				<el-col :span=24>
					<el-form-item label="头像图片" prop="name">
						<el-upload
							class="avatar-uploader"
							action="https://tengxiansh.dindong.cn/api/file/upload-img"
							name="photo"
							:show-file-list="false"
							:on-success="handlePhoto"
							:before-upload="beforeAvatarUpload">
							<img v-if="photoImg" :src="photoImg" class="avatar">
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-col :span="14">
						<el-form-item label="性别" prop="sex">
							<el-radio-group v-model="addForm.sex" >
								<el-radio class="radio" :label="0">保密</el-radio>
								<el-radio class="radio" :label="1">男</el-radio>
								<el-radio class="radio" :label="2">女</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="10">
						<el-form-item label="年龄" prop="age" label-width="80px">
							<el-input v-model="addForm.age" style="width:80px" ></el-input>
						</el-form-item>
					</el-col>
				</el-col>
				<el-col :span="24">
						<el-form-item label="籍贯" prop="origin">
							<!-- <el-cascader
								placeholder="选择地址"
								style="width:300px"
								:options="ORIGIN"
								:props="{value:'label'}"
								v-model="addForm.origin"
								class="cascader"
								filterable></el-cascader>

								<el-input v-model="addForm.originTown" placeholder="输入镇街" style="width:200px;"></el-input> -->
								<el-select v-model="addForm.birthplace" filterable placeholder="请选择">
								<el-option
									v-for="item in birthplaceOptions"
									:key="item.value"
									:label="item.label"
									:value="item.value"
									>
								</el-option>
							</el-select>
						</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="所在地区" prop="userAddress" >
							<el-cascader
							style="width:300px"
							placeholder="选择地址"
							change-on-select
							:disabled="addForm.is_vip==1"
							:options="ORIGIN"
							:props="{value:'label'}"
							v-model="addForm.userAddress"
							class="cascader"
							filterable></el-cascader>
					</el-form-item>
				</el-col>
				<el-col :span=24>
					<el-form-item label="激活状态" prop="status">
						<!-- <div v-if="addForm.activity">激活</div>
						<div v-else>未激活</div> -->
						<el-radio-group v-model="addForm.activity" >
								<el-radio class="radio" :label="0">未激活</el-radio>
								<el-radio class="radio" :label="1">已激活</el-radio>
							</el-radio-group>
					</el-form-item>
				</el-col>


				<el-col :span="24" style="display:flex;justify-content:space-around；align-item:center">
					<el-col :span="12">
						<el-form-item label="入会时间" prop="admissionTime">
							<el-date-picker value-format="yyyy-MM-dd HH:mm:ss" type="date" placeholder="选择日期" v-model="addForm.admissionTime" ></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="会员到期时间" prop="expires" label-width="100px">
						<el-date-picker value-format="yyyy-MM-dd HH:mm:ss" type="date" placeholder="选择日期" v-model="addForm.expires" ></el-date-picker>
					</el-form-item>
					</el-col>
				</el-col>
				<el-col :span="24">
					<el-form-item label="角色">
						<el-checkbox-group  v-model="addForm.checked">
							<el-checkbox v-for="character in roleList" :label="character.id" :key="character.id">{{character.display_name}}</el-checkbox>
						</el-checkbox-group>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="会员电子资料" label-width="120px">
						<el-button type="primary" @click="addMemberPicDetail">添加</el-button>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item>
						<div class="memberPicWrapper">
							<div class="memberPicDetail" v-for="(item,index) of addForm.memberPicDetail" :key="index" @click="prevImg(item.imgUrl)">
								<img :src="item.imgUrl" alt="">
								<div>{{item.desc}}</div>
								<img src="../../../static/images/delete.png" alt="" class="delete" @click.stop="deleteMemberPicDetail(item,index)">
							</div>
						</div>
					</el-form-item>
				</el-col>
				<!-- <el-col :span="24">
					<el-form-item label="会费标准" prop="cost">
						<el-select v-model="addForm.cost" placeholder="请选择" disabled>
							<el-option
								v-for="item in costOptions"
								:key="item.value"
								:label="item.label"
								:value="item.value">
							</el-option>
						</el-select>
						<div>{{addForm.cost}}</div>
					</el-form-item>
				</el-col> -->

				<el-col :span="24">
					<div style="margin-bottom:20px">会员简介</div>
					<el-input type="textarea" v-model="addForm.intro" ></el-input>
				</el-col>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm('addForm')" >提交</el-button>
			</div>
		</el-dialog>
		<!-- 更改 end -->

		<!-- 添加会员电子资料 -->
		<el-dialog title="添加会员电子资料" :visible.sync="memberPicDetailVisible">
			<el-form>
				<el-form-item label="标题">
					<el-input v-model="memberPicTit" palceholder="输入标题"></el-input>
				</el-form-item>
				<el-form-item label="上传图片">
					<el-upload
                        class="avatar-uploader"
                        action="https://tengxiansh.dindong.cn/api/file/upload-img"
						name="photo"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="memberPicImg" :src="memberPicImg" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitMemberPic">添加</el-button>
			</div>
		</el-dialog>
		<!-- 添加会员电子资料 -->

		<!-- 图片预览 -->
		<el-dialog :visible.sync="prevImgVisible" size="tiny" center width="500px">
			<div style="display:flex;justify-content:center">
				<img style="max-width:100%" :src="dialogImageUrl" alt="">
			</div>
		</el-dialog>
		<!-- 图片预览 end -->
    </div>
</template>
<script>
import ORIGIN from '../../assets/json/origin.json';

export default {
	name:'managementMembership',//更改会员弹窗
	data() {
		return {
			prevImgVisible:false,//图片预览的显示
			addFormVisible:false,
			memberPicDetailVisible:false,//会员电子资料的显示
			imgPrevState:'',
			dialogImageUrl:'',//预览的图片地址
			ORIGIN,
			addFormRules: {
				name: [
					{ required: true, message: '请输入姓名', trigger: 'blur' }
				],
				phone: [
					{ required: true, message: '请输入手机号', trigger: 'blur' }
				],
				// sex: [
				// 	{ required: true, message: '请选择性别', trigger: 'blur' }
				// ],
				age: [
					{ required: true, message: '请输入年龄', trigger: 'blur' }
				],
				level: [
					{ required: true, message: '请输入会员等级', trigger: 'blur' }
				],
				origin: [
					{ required: true, message: '请输入籍贯', trigger: 'blur' }
				],
				admissionTime: [
					{ required: true, message: '请输入入会时间', trigger: 'blur' }
				],
			},
			payModeFlag:true,//能否选择缴费方式
			phoneList:[],//新增会员的搜索手机列表
			loading:false,//搜索手机列表的loading
			//新增界面数据
			addForm: {
				activity:'',//true为激活，false为未激活
                is_vip:'',//是否已经为vip，1只能编辑不能新增
				number:'',//会员编号
				realname: '',
				idCard:'',
                status:'',//激活状态
				phone:'',
				sex: '',
				age: '',
				level: '',
				// origin:'',//籍贯
				// originTown:'',//籍贯的镇
				// userAddress:'',//所在地
				birthplace:'',
				admissionTime:'',//入会时间
				cost:'',
				expires:'',//到期时间
				intro:'',//会员简介
				memberPicDetail:[
					//会员电子资料
				],
				checked:[]//角色权限
			},
			memberPicTit:'',//会员电子资料的标题
			memberPicImg:'',//会员电子资料的图片
			memberPicId:'',//会员电子资料的图片id
			//会员级别
			levelOptions: [],
			//会费标准
			id:'',
			receivedChangeFlag:true,//会员等级发生改变才能进行缴费状态的选择
			photoImg:'',//会员头像
			photoId:'',
			birthplaceOptions:[{label:"平福乡",value:"平福乡"},{label:"宁康乡",value:"宁康乡"},{label:"藤州镇",value:"藤州镇"},{label:"塘步镇",value:"塘步镇"},{label:"琅南镇",value:"琅南镇"},{label:"同心镇",value:"同心镇"},{label:"金鸡镇",value:"金鸡镇"},{label:"新庆镇",value:"新庆镇"},{label:"象棋镇",value:"象棋镇"},{label:"岭景镇",value:"岭景镇"},{label:"天平镇",value:"天平镇"},{label:"蒙江镇",value:"蒙江镇"},{label:"和平镇",value:"和平镇"},{label:"太平镇",value:"太平镇"},{label:"古龙镇",value:"古龙镇"},{label:"东荣镇",value:"东荣镇"},{label:"大黎镇",value:"大黎镇"},{label:"其它",value:"其它"}],
			roleList:[]
		}
	},
	watch:{
		addForm:{
			handler:function(nval){

				if(nval.level){
					this.payModeFlag=false;//先选中会员等级才能选缴费方式
				}else{
					this.payModeFlag=true;
                }
			},
			deep:true
		},
		'addForm.phone':function(val){
			if(val.length==''){
				this.activity=false;//true为激活，false为未激活
				this.addForm.is_vip='';//是否已经为vip，1只能编辑不能新增
				this.addForm.number='';
				this.addForm.realname='';
				this.addForm.status='';
				this.addForm.sex='';
				this.addForm.age='';
				this.addForm.received='';
				this.addForm.payMode='';
				this.addForm.level='';
				this.addForm.origin='';
				this.addForm.admissionTime='';
				this.addForm.companyList=[{
					unit:'',
					address: '',
					addressdetail:'',
					position:''
				}],//多家企业
				this.addForm.cost='';
				this.addForm.expires='';
				this.addForm.intro='';
				this.addForm.memberPicDetail=[];
			}
		}
    },
	methods: {
		beforeAvatarUpload(file) {
			//上传照片前的操作
			console.log(file,555)
		},
		handlePhoto(res, file) {
			//上传头像成功
			if(res.data){
				this.photoImg=res.data.img_url;
				this.photoId=res.data.id;
			}
		},
        handleAvatarSuccess(res, file) {
			//上传照片成功
			if(res.data){
				this.memberPicImg=res.data.img_url;
				this.memberPicId=res.data.id;
			}
		},
		prevImg(url){
			this.dialogImageUrl=url;
			this.prevImgVisible=true;
		},
		addMemberPicDetail(){
			//添加电子资料
			this.memberPicDetailVisible=true;
		},
		submitMemberPic(){
			this.memberPicDetailVisible=false;
			const obj={
				imgUrl:this.memberPicImg,
				imgId:this.memberPicId,
				desc:this.memberPicTit
			}
			this.memberPicImg='';
			this.memberPicId='';
			this.memberPicTit='';
			if(this.addForm.memberPicDetail instanceof Array==false){
				this.addForm.memberPicDetail=[]
			}
			this.addForm.memberPicDetail.push(obj);
		},
		deleteMemberPicDetail(item,index){
			//删除电子资料
			console.log('删除了电子资料')
			this.addForm.memberPicDetail.splice(index,1);
			this.$forceUpdate();
			console.log(this.addForm.memberPicDetail)
		},
		showDialog(id,vipId){
            this.addFormVisible=true;
            this.id=id;
            this.vipId=vipId
            this.getUserVipUpdate(id,vipId)
		},
        async getUserVipUpdate(id,vipId){
            //修改会员信息

            const res=await this.$api.getUserVipDetail({
                id:id,
                vipId:vipId
            });
            const memberDetail=res.data.data.user_vip_info;
			this.addForm.realname=memberDetail.realname;
			this.addForm.idCard=memberDetail.id_card;
			this.addForm.status=+memberDetail.status;
			this.addForm.activity=+memberDetail.status;
            this.addForm.phone=memberDetail.phone;
            this.addForm.sex=+ memberDetail.sex;
            this.addForm.age=memberDetail.age;
            this.addForm.received=memberDetail.received;
			this.addForm.level=memberDetail.vip_code;
			this.initLevel=memberDetail.vip_code;//初始状态的会员等级
            setTimeout(()=>{
                this.addForm.payMode= memberDetail.pay_mode;
            },500)
			this.addForm.admissionTime=memberDetail.start_time;
			this.addForm.expires=memberDetail.end_time;

			//企业信息
			// this.addForm.origin=[memberDetail.home_province,memberDetail.home_city,memberDetail.home_area];
			this.addForm.birthplace=memberDetail.birthplace;//籍贯
			if(memberDetail.user_province &&memberDetail.user_city&&memberDetail.user_area){
				this.addForm.userAddress=[memberDetail.user_province,memberDetail.user_city,memberDetail.user_area];
			}else if(memberDetail.user_province &&memberDetail.user_city &&!memberDetail.user_area){
				this.addForm.userAddress=[memberDetail.user_province,memberDetail.user_city];
			}else if(memberDetail.user_province &&!memberDetail.user_city &&!memberDetail.user_area){
				this.addForm.userAddress=[memberDetail.user_province];
			}
			// this.addForm.originTown=memberDetail.home_address;

			this.photoId=memberDetail.photo_id;
			this.photoImg=memberDetail.vip_thumb;
			this.addForm.checked=memberDetail.role_id_list;

			//电子资料
			const digital=[];
			memberDetail.telecom.forEach(item=>{
				let obj={};
				obj.imgUrl=item.thumb;
				obj.imgId=item.photo_id;
				obj.desc=item.title;
				digital.push(obj)

			})

			this.addForm.memberPicDetail=digital;
			this.addForm.intro=memberDetail.description
            this.addFormVisible=true;
        },
        submitForm(formName) {
            //提交表单验证   
            this.$refs[formName].validate((valid) => {
            if (valid) {
                    this.getUserVipUpdateHandle(this.id,this.vipId);//更新会员信息

            } else {
                console.log('error submit!!');
                return false;
            }
            });
          },
        async getUserVipUpdateHandle(){
			//更新会员信息
				//电子信息
				const msg=this.addForm;
			  const digital=msg.memberPicDetail||[];
			  let memberPicDetailt=[];
			  digital.forEach(item=>{
				  if(item){
					  let obj={};
						obj.id=item.imgId;
						obj.title=item.desc;
						memberPicDetailt.push(obj);
				  }
			  })
              const req=await this.$api.getUserVipUpdate({
                  	realname:msg.realname,
                    phone:msg.phone,
                    age:msg.age,
					idCard:msg.idCard,
					telecoms:memberPicDetailt,
                    vipCode:msg.level,//会员等级
                    payMode:msg.payMode,//1全款 2分期
                    areaCode:'0001',
					sex:msg.sex,
					status:msg.activity,
                    // homeProvince:msg.origin[0],
                    // homeCity:msg.origin[1],
					// homeArea:msg.origin[2],
					// homeAddress:msg.originTown,
					birthplace:msg.birthplace,
					userProvince:msg.userAddress[0]||'',
                    userCity:msg.userAddress[1]||'',
					userArea:msg.userAddress[2]||'',
					startTime:msg.admissionTime,
					servingTime:msg.expires,
					description:msg.intro,
                  id:this.id,
				  vipId:this.vipId,
				  photo_id:this.photoId,
				  role_id:msg.checked
              })
              if(req.data.level=='success'){
                  this.$message({
                      message: req.data.message,
                      type: 'success'
                      });
                      this.$emit('update')
                  this.addFormVisible=false;
              }else{
                  this.$message({
                  message: req.data.message,
                  type: 'error'
                  });
              }
		},
		//获取角色列表
			async getRoleList(){
			const res = await this.$api.getRoleList();
			if(res.data.level=='success'){
				this.roleList = res.data.data;
			}else{
				this.$message({
				message: res.data.message,
				type: 'error'
				});
			}
			},
        closeDialog(){
            //重置数据
            this.id='';
            this.vipId=''
            this.addForm= {
				activity:'',//true为激活，false为未激活
                is_vip:'',//是否已经为vip，1只能编辑不能新增
				number:'',//会员编号
				realname: '',
				idCard:'',
                status:'',//激活状态
				phone:'',
				sex: '',
				age: '',
				level: '',
				// origin:'',//籍贯
				// originTown:'',//籍贯的镇
				// userAddress:'',//所在地
				birthplace:'',
				admissionTime:'',//入会时间
				cost:'',
				expires:'',//到期时间
				intro:'',//会员简介
				memberPicDetail:[
					//会员电子资料
				],
				checked:[]
			}
        },
	},
	mounted() {
		this.getRoleList();
    },

}
</script>
<style lang="scss" scoped>
	.address-detail{
			margin-top:20px;
		}

		.dialog-footer{
			text-align: center;
		}
	.address-detail{
			margin-top:20px;
		}
	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
		border: 1px dashed #d9d9d9;
	}
	.avatar {
		width: 178px;
		height: 178px;
		display: block;
		object-fit: contain;
	}
	.memberPicWrapper{
		display:flex;
		flex-wrap: wrap;
	}
	.memberPicDetail{
		text-align: center;
		margin:0 10px;
		position: relative;
		img{
			width:120px;
			height: 120px;
			object-fit: cover;
			margin:20px;
		}
		.delete{
			width:40px;
			height: 40px;
			position: absolute;
			top:-20px;
			right:-20px;
		}
	}
</style>

